package com.glory.dgcpcpda.activity.mfg;

import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.adapter.AddCarrierDataAdapter;
import com.glory.dgcpcpda.adapter.MantissaLotListAdapter;
import com.glory.dgcpcpda.adapter.SampleListAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.entity.AdrefListEntity;
import com.glory.dgcpcpda.entity.HOLDEntity;
import com.glory.dgcpcpda.entity.LotList;
import com.glory.dgcpcpda.entity.LotMulticarrierList;
import com.glory.dgcpcpda.entity.SimpleEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.LotUtils;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * FileName: FTTrackOutBiandaiErrorActivity
 * Author: XJH
 * Date: 2020/5/22 10:15
 * Description:FT测试编带出站，异常出站
 * History:
 */
public class FTTrackOutBiandaiErrorActivity extends BaseActivity {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.tvMessage)
    TextView tvMessage;
    @BindView(R.id.tvLot)
    TextView tvLot;
    @BindView(R.id.tvPackageType)
    TextView tvPackageType;
    @BindView(R.id.tvLotQTY)
    TextView tvLotQTY;
    @BindView(R.id.tvSubmit1)
    TextView tvSubmit1;
    @BindView(R.id.list_titleLayout)
    LinearLayout listTitleLayout;
    @BindView(R.id.rvTestList)
    RecyclerView rvTestList;
    @BindView(R.id.rvItemLotList)
    RecyclerView rvItemLotList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.etBingLotID)
    FreeUI_ClearEditText etBingLotID;
    @BindView(R.id.rvLotList)
    RecyclerView rvLotList;
    private AddCarrierDataAdapter lotListAdapter;
    private MantissaLotListAdapter mTestAdapter;
    private MantissaLotListAdapter mMantissaLotListAdapter;
    private String mEqpid;
    private String ISERROROUT;
    private List<String> stopCodeList = new ArrayList<>();
    private List<String> responsibilityGroupList= new ArrayList<>();
    private FreeUI_GeneralPop stopCodePop;
    private FreeUI_GeneralPop groupPop;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_track_out_biandai_error_ft;
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        setMainLayout(llMain);
        addActivity(this);
        tvBaseSubmit.setVisibility(View.GONE);
        tvTitle.setText("异常结束-(FT测试)");
        tvLot.setText(bundle.getString("LOTID"));
        tvPackageType.setText(bundle.getString("PACKAGETYPE"));
        mEqpid = bundle.getString("EQPID", "");
        ISERROROUT = bundle.getString("ISERROROUT");
        tvLotQTY.setText(bundle.getString("LOTNUM"));
        initRecyclerView(rvItemLotList,this);
        initRecyclerView(rvLotList, this);
        initRecyclerView(rvTestList,this);
        mTestAdapter = new MantissaLotListAdapter(null,false);
        lotListAdapter = getCarrierAdapter();
        rvLotList.setAdapter(lotListAdapter);
        mTestAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mTestAdapter.isFirstOnly(true);
        rvTestList.setAdapter(mTestAdapter);
        mMantissaLotListAdapter = new MantissaLotListAdapter(null,false);
        mMantissaLotListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mMantissaLotListAdapter.isFirstOnly(true);
        rvItemLotList.setAdapter(mMantissaLotListAdapter);
        initEdit(etBingLotID,s->{
            if (lotListAdapter.getData().contains(s)){
                showToast("当前载具已添加",false);
                return;
            }
            LotUtils.checkCarrier(FTTrackOutBiandaiErrorActivity.this,tvLot.getText().toString(),s, getSupportFragmentManager(), new LotUtils.netCallback<Object>() {

                @Override
                public void onSuccess(Object response) {
                    lotListAdapter.addData(s);
                    etBingLotID.setText("");
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t, "CHECKCARRIER");
                }
            });
        });
    }

    @Override
    protected void initData() {
        requestData("SelectBinData");
        getAdrefListEntity("CPC_FT_SPECIAL_HOLD_OWNER");
        getAdrefListEntity("CPC_FT_SPECIAL_HOLD_CODE");
    }

    private void getAdrefListEntity(String name) {
        FreeUI_EntityCallBack<BaseResponseBean<AdrefListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<AdrefListEntity>>
                (new TypeToken<BaseResponseBean<AdrefListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<AdrefListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    List<AdrefListEntity.Adref> adreflist = response.body().getResponse().getBody().getADREFLIST();
                    if (adreflist.size() > 0){
                        for (AdrefListEntity.Adref entity : adreflist)  {
                            if (name.equals("CPC_FT_SPECIAL_HOLD_CODE")){
                                stopCodeList.add(entity.getKEY() + "/" + entity.getDESCRIPTION());
                            }else {
                                responsibilityGroupList.add(entity.getKEY() + "/" + entity.getDESCRIPTION());
                            }
                        }
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<AdrefListEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"ADREFLISTQUERY");

            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("REFERENCETYPE","USER");
        map.addProperty("REFERENCENAME",name);
        NetUtils.requestPostNet("CPC.ADREFLISTQUERY","ADREFLISTQUERY",this,map,callBack);
    }

    @OnClick({R.id.tvSubmit1,R.id.tvSubmit2})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.tvSubmit2){
            if (actionControl("Abnormal"))
                return;

            showSubmitDialog(new onSubmitListener() {
                @Override
                public void setOnSubmitListener() {
                    requestData("AbnormalTrackOut");
                }
            },"确定要异常出站吗？");

        }else {
            if (actionControl("StayLotAbnormal"))
                return;
            submit("Y");


        }

    }

    private void submit(String SHOWMSG) {

//        if (lotListAdapter.getData().size() <=0){
//            showToast("请添加载具",false);
//            return;
//        }

        FreeUI_EntityCallBack<BaseResponseBean<SimpleEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<SimpleEntity>>
                (new TypeToken<BaseResponseBean<SimpleEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<SimpleEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    SimpleEntity entity = response.body().getResponse().getBody();
                    if (entity.getTRACKSHOWMSG().equals("")){
                        showConfirmDialogFinishAll("出站成功");
                    }else {
                        showSubmitDialog(() -> submit("N"),entity.getTRACKSHOWMSG());
                    }

                }


            }

            @Override
            public void onError(Response<BaseResponseBean<SimpleEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "LOTFTTRACKOUT");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "AbnormalTrackOut");
        map.addProperty("EQUIPMENTID", mEqpid);
        map.addProperty("SHOWMSG", SHOWMSG);
        map.addProperty("STAYENDLOT", true);
        List<LotList> lotList = new ArrayList<>();
        lotList.add(new LotList(tvLot.getText().toString()));
        map.add("LOTLIST", new JsonParser().parse(new Gson().toJson(lotList)).getAsJsonArray());
        ArrayList<LotMulticarrierList> lotMulticarrierLists = new ArrayList<>();
        for (String s:lotListAdapter.getData()) {
            LotMulticarrierList lotMulticarrier = new LotMulticarrierList();
            lotMulticarrier.setCARRIERID(s);
            lotMulticarrierLists.add(lotMulticarrier);
        }
        map.add("LOTMULTICARRIERLIST",new JsonParser().parse(new Gson().toJson(lotMulticarrierLists)).getAsJsonArray());
        NetUtils.requestPostNet("CPC.LOTFTTRACKOUT", "LOTFTTRACKOUT", this, map, callBack);
    }

    private void requestData(String actionType){
        FreeUI_EntityCallBack<BaseResponseBean<SimpleEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<SimpleEntity>>
                (new TypeToken<BaseResponseBean<SimpleEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<SimpleEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    SimpleEntity entity = response.body().getResponse().getBody();
                    if (actionType.equals("AbnormalTrackOut")){
                        showConfirmDialogFinishAll(entity.getTRACKSHOWMSG().equals("") ? "出站成功" : entity.getTRACKSHOWMSG());
                        return;
                    }
                    if (!entity.getTRACKSHOWMSG().equals("")){
                        showConfirmDialog(entity.getTRACKSHOWMSG());
                    }
                    if (entity.getLOTBINDATALIST().size() <= 0){
                        showToast("暂无测试数据",false);
                    }else if (entity.getMANTISSALOTBINDATALIST().size() <= 0){
                        showToast("暂无尾数批次信息",false);
                    }

                    ArrayList<Double> strings = new ArrayList<>();

                    for(SimpleEntity.MantissaLotBinData entry : entity.getLOTBINDATALIST()){
                        String[] ns = entry.getBINNAME().split("N");
                        String binName = "";
                        if (ns[1].contains("_")){
                            binName = ns[1].replace("_",".");
                        }else{
                            binName = ns[1];
                        }
                        strings.add(Double.parseDouble(binName));
                        entry.setCODE(Double.parseDouble(binName));
                    }
                    Collections.sort(strings);
                    List<SimpleEntity.MantissaLotBinData> simpleEntityList = new ArrayList<>();
                    for (Double s:strings) {
                        for (SimpleEntity.MantissaLotBinData sm:entity.getLOTBINDATALIST()) {
                            if (s == sm.getCODE()){
                                simpleEntityList.add(sm);
                            }
                        }
                    }

                    mTestAdapter.setNewData(simpleEntityList);
                    mMantissaLotListAdapter.setNewData(entity.getMANTISSALOTBINDATALIST());
                }


            }

            @Override
            public void onError(Response<BaseResponseBean<SimpleEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "LOTFTTRACKOUT");
            }
        };


        if ("true".equals(ISERROROUT)){
            errorOut();
        }else {

//            if (lotListAdapter.getData().size() <=0){
//                showToast("请添加载具",false);
//                return;
//            }

            JsonObject map = new JsonObject();
            map.addProperty("ACTIONTYPE", actionType);
            map.addProperty("EQUIPMENTID", mEqpid);
            List<LotList> lotList = new ArrayList<>();
            lotList.add(new LotList(tvLot.getText().toString()));
            map.add("LOTLIST", new JsonParser().parse(new Gson().toJson(lotList)).getAsJsonArray());
            ArrayList<LotMulticarrierList> lotMulticarrierLists = new ArrayList<>();
            for (String s:lotListAdapter.getData()) {
                LotMulticarrierList lotMulticarrier = new LotMulticarrierList();
                lotMulticarrier.setCARRIERID(s);
                lotMulticarrierLists.add(lotMulticarrier);
            }

            map.add("LOTMULTICARRIERLIST",new JsonParser().parse(new Gson().toJson(lotMulticarrierLists)).getAsJsonArray());
            NetUtils.requestPostNet("CPC.LOTFTTRACKOUT", "LOTFTTRACKOUT", this, map, callBack);
        }
    }

    private void errorOut() {
        FreeUI_GeneralFragmentDialog freeU_generalFragmentDialog = new FreeUI_GeneralFragmentDialog();
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_errorout, null);
        TextView tvCancel = view.findViewById(R.id.tvCancel);
        TextView tvConfirm = view.findViewById(R.id.tvConfirm);
        EditText etReason = view.findViewById(R.id.etReason);
        FrameLayout flHoldCodeList = view.findViewById(R.id.flHoldCodeList);
        TextView tvHoldCode = view.findViewById(R.id.tvHoldCode);
        ImageView ivHoldCodeArrow = view.findViewById(R.id.ivHoldCodeArrow);
        FrameLayout flHoldownerList = view.findViewById(R.id.flHoldownerList);
        TextView tvHoldowner = view.findViewById(R.id.tvHoldowner);
        ImageView ivHoldownerArrow = view.findViewById(R.id.ivHoldownerArrow);
        EditText etBingLotID = view.findViewById(R.id.etBingLotID);
        RecyclerView rvLotList = view.findViewById(R.id.rvLotList);

        initRecyclerView(rvLotList, this);
        AddCarrierDataAdapter mLotListAdapter = getCarrierAdapter();
        rvLotList.setAdapter(mLotListAdapter);

        initEdit(etBingLotID,s->{
            if (mLotListAdapter.getData().contains(s)){
                showToast("当前载具已添加",false);
                return;
            }
            mLotListAdapter.addData(s);
            etBingLotID.setText("");
            etBingLotID.requestFocus();
        });

        flHoldCodeList.setOnClickListener(v ->{
            if (stopCodePop != null) {
                if (stopCodePop.isShowing()) {
                    stopCodePop.dismiss();
                }
            } else {
                stopCodePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flHoldCodeList.getWidth(), stopCodeList, ivHoldCodeArrow, (codeS, i) -> {
                    tvHoldCode.setText(codeS);
                });
            }
            FreeApi_PopUtils.setArrowShow(ivHoldCodeArrow);
            stopCodePop.showAsDropDown(flHoldCodeList, 0, 0);
        });

        flHoldownerList.setOnClickListener(v ->{
            if (groupPop != null) {
                if (groupPop.isShowing()) {
                    groupPop.dismiss();
                }
            } else {
                groupPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flHoldownerList.getWidth(), responsibilityGroupList, ivHoldownerArrow, (codeS, i) -> {
                    tvHoldowner.setText(codeS);
                });
            }
            FreeApi_PopUtils.setArrowShow(ivHoldownerArrow);
            groupPop.showAsDropDown(flHoldownerList, 0, 0);
        });

        tvCancel.setOnClickListener(view1 -> {
            freeU_generalFragmentDialog.dismiss();
        });
        tvConfirm.setOnClickListener(v -> {

//            if (mLotListAdapter.getData().size() <=0){
//                showToast("请添加载具",false);
//                return;
//            }

            if (tvHoldowner.getText().toString().equals("")){
                showToast("请选择责任组",false);
                return;
            }

            if (tvHoldCode.getText().toString().equals("")){
                showToast("请选择暂停码",false);
                return;
            }
            if (tvHoldCode.getText().toString().equals("其他原因/其他原因")){
                if (etReason.getText().toString().equals("")){
                    showToast("暂停原因必填！",false);
                    return;
                }
            }

            FreeUI_EntityCallBack<BaseResponseBean<SimpleEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<SimpleEntity>>
                    (new TypeToken<BaseResponseBean<SimpleEntity>>() {
                    }.getType(), getSupportFragmentManager(), this) {

                @Override
                public void onSuccess(Response<BaseResponseBean<SimpleEntity>> response) {
                    super.onSuccess(response);
                    if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                        SimpleEntity entity = response.body().getResponse().getBody();
                        showConfirmDialogFinishAll(entity.getTRACKSHOWMSG().equals("") ? "出站成功" : entity.getTRACKSHOWMSG());
                        new Handler().postDelayed(() -> {
                            freeU_generalFragmentDialog.dismiss();
                            finish();
                        },1000);

                    }
                }

                @Override
                public void onError(Response<BaseResponseBean<SimpleEntity>> response) {
                    super.onError(response);
                    loadError(response.getException(), "LOTFTTRACKOUT");
                }
            };


            if (tvHoldCode.getText().toString() == null){
                showToast("请选择暂停码",false);
                return;
            }
            if (tvHoldowner.getText().toString() == null){
                showToast("请选择暂停责任组",false);
                return;
            }

            HOLDEntity holdEntity = new HOLDEntity();
            String[] holdCode = tvHoldCode.getText().toString().split("/");
            String[] holdowner = tvHoldowner.getText().toString().split("/");
            holdEntity.setHOLDCODE(holdCode[0]);
            holdEntity.setHOLDREASON(getText(etReason));
            holdEntity.setHOLDOWNER(holdowner[0]);
            JsonObject map = new JsonObject();
            map.addProperty("ACTIONTYPE", "AbnormalTrackOut");
            map.addProperty("EQUIPMENTID", mEqpid);
            map.addProperty("ABORTFTSPECIAL",true);
            map.addProperty("ABNORMALTRACKOUTSPECIAL","Y");
            map.add("XLOTHOLD",new JsonParser().parse(new Gson().toJson(holdEntity)).getAsJsonObject());

            List<LotList> lotList = new ArrayList<>();
            lotList.add(new LotList(tvLot.getText().toString()));
            map.add("LOTLIST", new JsonParser().parse(new Gson().toJson(lotList)).getAsJsonArray());

            ArrayList<LotMulticarrierList> lotMulticarrierLists = new ArrayList<>();
            for (String s:mLotListAdapter.getData()) {
                LotMulticarrierList lotMulticarrier = new LotMulticarrierList();
                lotMulticarrier.setCARRIERID(s);
                lotMulticarrierLists.add(lotMulticarrier);
            }
            map.add("LOTMULTICARRIERLIST",new JsonParser().parse(new Gson().toJson(lotMulticarrierLists)).getAsJsonArray());
            NetUtils.requestPostNet("CPC.LOTFTTRACKOUT", "LOTFTTRACKOUT", this, map, callBack);

        });

        freeU_generalFragmentDialog.setLayout(view);
        freeU_generalFragmentDialog.show(getSupportFragmentManager(), "SUBMIT_DIALOG");
    }

}
